package org.opens.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import org.opens.dao.ShiroRoleDao;
import org.opens.dao.ShiroUserWithRoleDao;
import org.opens.entity.ShiroRole;
import org.opens.entity.ShiroUserWithRole;
import org.opens.service.ShiroRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Service
public class ShiroRoleServiceImpl implements ShiroRoleService {

    @Autowired
    private ShiroUserWithRoleDao shiroUserWithRoleDao;

    @Autowired
    private ShiroRoleDao shiroRoleDao;

    @Override
    public List<ShiroRole> findByUserId(Integer userId) {
        Assert.notNull(userId, "传入的userId不能为null");

        List<ShiroUserWithRole> shiroUserWithRoles = shiroUserWithRoleDao.findByUserId(userId);
        List<ShiroRole> shiroRoles = Collections.emptyList();
        if (CollectionUtil.isNotEmpty(shiroUserWithRoles)) {
            Set<Integer> roleIds = shiroUserWithRoles.stream().map(ShiroUserWithRole::getRoleId).collect(Collectors.toSet());
            shiroRoles = shiroRoleDao.selectBatchIds(roleIds);
        }

        return shiroRoles;
    }

}
